package demo03

import (
	"fmt"
	"time"
)

// 优雅封装Golang的配置项
// https://juejin.cn/post/7400206885880627263?utm_source=gold_browser_extension#heading-5

type Server03 struct {
	addr     string
	port     string
	timeout  time.Duration
	maxConns int
}

type ServerBuilder struct {
	Server03
}

func (sb *ServerBuilder) Create(addr, port string) *ServerBuilder {
	sb.addr = addr
	sb.port = port
	return sb
}

func (sb *ServerBuilder) WithTimeout(timeout time.Duration) *ServerBuilder {
	sb.timeout = timeout
	return sb
}

func (sb *ServerBuilder) WithMaxConns(maxConns int) *ServerBuilder {
	sb.maxConns = maxConns
	return sb
}

func (sb *ServerBuilder) Build() *ServerBuilder {
	// 下面是默认值处理
	if sb.timeout == 0 {
		sb.timeout = 5 * time.Millisecond
	}
	if sb.maxConns == 0 {
		sb.maxConns = 20
	}
	return sb
}

// BuilderDemo
// 其实就是在Server对象外部包了一层ServerBuilder，最后在ServerBuilder.Build()中返回了Server对象
// 其实这个方法挺完美，满足了我们之前提的全部需求，但是问题在于，golang中的err处理，在这种方式中不是很好体现
func BuilderDemo() {
	sb := new(ServerBuilder)
	server03 := sb.Create("127.0.0.1", "8080").
		WithTimeout(3 * time.Second).
		WithMaxConns(100).
		Build()
	fmt.Println(server03)
}
